#include "head.h"
#include "disk.h"
#include "ext2.h"
#include<string.h>
#include<stdio.h>

char whitespace[] = " \t\r\n\v";

int getcmd(char* buf, int nbuf);
void parsecmd(char* buf, char* argv[], int* argc);
void runcmd(char* argv[], int *argc); //运行命令

int main(){
    init_ext2();
    char buf[100];
    while(getcmd(buf, 100) >= 0)
    {
        char *argv[100];
        int argc;
        parsecmd(buf, argv, &argc);
        runcmd(argv, &argc);
    }
}

int getcmd(char* buf, int nbuf) //从缓冲区中读取命令
{
    printf("==> ");
    memset(buf, 0, nbuf);
    gets(buf, nbuf);
    if(buf[0] == 0)
        return -1;
    return 0;
}

void parsecmd(char* buf, char* argv[], int* argc) //将命令中的变量存入到argv[]中，变量数存入argc
{
    int i,j;
    i = 0;
    // 遍历寻找所有变量
    for(j = 0; buf[j] != '\n' && buf[j] != '\0';j++){
        while(strchr(whitespace, buf[j]))
            j++; //将j指向变量的开头
        argv[i++] = buf + j;
        while(!strchr(whitespace, buf[j]))
            j++; //将j指向当前变量的末尾
        buf[j] = '\0';
    }
    argv[i] = 0;
    *argc = i;
}

void runcmd(char* argv[], int *argc) //运行命令
{
    if(strcmp(argv[0], "ls") == 0){
        ls(argv, argc);
    }
    else if(strcmp(argv[0], "mkdir") == 0){
        mkdir(argv, argc);
    }
    else if(strcmp(argv[0], "touch") == 0){
        touch(argv, argc);
    }
    else if(strcmp(argv[0], "cp") == 0){
        cp(argv, argc);
    }
    else if(strcmp(argv[0], "shutdown") == 0){
        printf("shutdown..\n");
        shutdown();
    }
    else
    {
        printf("Unknown commands!\n");
        return;
    }
    
}